<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { caresiteFormSchema } from './caresite.data';
  import { ref, unref, computed } from 'vue';
  import { careSiteAddApi, careSiteUpdateApi } from '@/api/hopefly/api';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const rowId = ref('');
  const [registerForm, { validate, setFieldsValue }] = useForm({
    baseColProps: { span: 24 },
    schemas: caresiteFormSchema,
    showActionButtonGroup: false,
  });
  const [registerModal, { closeModal, setModalProps }] = useModalInner((data) => {
    isUpdate.value = !!data?.isUpdate;
    data && onDataReceive(data);
  });
  function onDataReceive(data) {
    console.log('Data Received', data);
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        title: data.record.title,
        URL: data.record.url,
      });
    }
  }
  const getTitle = computed(() => (!unref(isUpdate) ? '新增标签' : '编辑标签'));

  async function handleSubmit() {
    try {
      const values: any = await validate();
      if (!unref(isUpdate)) {
        await careSiteAddApi(values);
      } else {
        values.id = rowId.value;
        await careSiteUpdateApi(values);
      }
      closeModal();
      emit('success', {});
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
